package com.yaorange.module.system.service.impl;

import com.yaorange.module.system.repository.SysPermissionRepository;
import com.yaorange.module.system.service.SysPermissionService;
import com.yaorange.module.system.service.SysRolePermissionService;
import com.yaorange.module.vo.SysPermissionTreeVo;
import com.yaorange.pojo.SysPermission;
import com.yaorange.response.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 15332
 * @version 1.0
 * @date 2025/6/19 15:58
 * @description 权限树业务层
 */
@Service
public class SysPermissionServiceImpl implements SysPermissionService {

  @Autowired
  private SysPermissionRepository repository;
  @Autowired
  private SysRolePermissionService service;
  /**
   * 获取权限树
   * @return
   */
  @Override
  public List<SysPermissionTreeVo> selectPermTree() {
    // 先获取到所有权限
    List<SysPermission> list = repository.selectPermTreeList();
    // 先使用map来封装权限对象
    HashMap<Long, SysPermissionTreeVo> treeVoMap = new HashMap<>();

    // 遍历整个权限集合
    for (int i = 0; i < list.size(); i++) {
      SysPermission sysPermission = list.get(i);
      SysPermissionTreeVo sysPermissionTreeVo = new SysPermissionTreeVo();
      sysPermissionTreeVo.setId(sysPermission.getPermId());
      sysPermissionTreeVo.setLabel(sysPermission.getPermTitle());
      sysPermissionTreeVo.setChildren(new ArrayList<>());
      treeVoMap.put(sysPermission.getPermId(),sysPermissionTreeVo);
    }
    // 构建权限树
    List<SysPermissionTreeVo> rootTree = new ArrayList<>();
    for (SysPermission sysPermission:list) {
      // 父菜单的编号，如果为空则是父节点，就是一级菜单
      if (sysPermission.getPermPid()==null){
        // 父菜单信息
        SysPermissionTreeVo parentVo = treeVoMap.get(sysPermission.getPermId());
        rootTree.add(parentVo);
      }else {
        // 否则就是当前节点是子节点
        // 拿到父节点，把这个子节点放到父结点中
        SysPermissionTreeVo parentVo = treeVoMap.get(sysPermission.getPermPid());
        parentVo.getChildren().add(treeVoMap.get(sysPermission.getPermId()));
      }
    }
    return rootTree;
  }

  /**
   * 根据角色id获取到该用户的权限id集合
   * @param id
   * @return
   */
  @Override
  public List<Long> selectPermById(Long id) {
    List<Long> ids = service.selectPermById(id);
    return ids;
  }

  /**
   * 获取全部权限的集合
   * @return
   */
  @Override
  public List<SysPermission> selectPerm() {
    return repository.selectPermTreeList();
  }


  /**
   * 根据当前的权限id获取到这个权限对象
   * @param id
   * @return
   */
  @Override
  public SysPermission selectPermissionById(Long id) {
    return repository.selectPerm(id);
  }

  /**
   * 权限状态
   * @param id
   * @param permStatus
   */
  @Override
  public void updateStatus(Long id, Long permStatus) {
    SysPermission sysPermission = repository.selectPerm(id);
    sysPermission.setPermStatus(permStatus);
    repository.update(sysPermission);
  }


}
